# 演示如何解析控制chrome的下载页面
# 需要展开shadowRoot

from selenium import webdriver

import time


def expand_root_element(element):
    ele = driver.execute_script("return arguments[0].shadowRoot;", element)
    return ele


options = webdriver.ChromeOptions()
options.add_argument('--disable-gpu')
driver = webdriver.Chrome(executable_path='/usr/local/bin/chromedriver', chrome_options=options)

driver.set_page_load_timeout(15)

driver.get('https://mirrors.aliyun.com/centos/8.0.1905/isos/x86_64/CentOS-8-x86_64-1905-dvd1.iso')

time.sleep(2)

driver.get('chrome://downloads/')

manager = driver.find_element_by_tag_name('downloads-manager')
# print(manager)
mgr_shadowRoot = expand_root_element(manager)
downloads = mgr_shadowRoot.find_element_by_id('downloadsList')
items = downloads.find_element_by_tag_name('downloads-item')
# print(items)
items_shadowRoot = expand_root_element(items)

# cancel the first download
url = items_shadowRoot.find_element_by_id('url')
print(url.get_attribute("href"))

buttons = items_shadowRoot.find_elements_by_tag_name('cr-button')
for button in buttons:
    if button.get_attribute("focus-type") == "cancel":
        print("click cancel")
        button.click()
        break
